import React, { useState, useEffect, useRef, useContext } from "react";
import { Typography, Spin, Alert, Card, Button } from "antd";
import { LoadingOutlined, SendOutlined } from "@ant-design/icons";
import AIEditor from "../../components/AIEditor";
import { MessageContext } from "../../App";
import CachedFlightSelectionModal from "./CachedFlightSelectionModal";
import {
  FlightOption,
  processTimeData,
  type TimeDataResult,
} from "../../services/apiService";
import { FlightState } from "./types";
import { useTranslation } from 'react-i18next';
import i18n from "../../locales/i18n";

// 环境变量配置
const CONTENT_API_BASE_URL = process.env.REACT_APP_CONTENT_API_BASE_URL || "http://localhost:7800";

interface ProductViewerProps {
  productId: string;
  flightState?: FlightState;
}

interface ProductData {
  pageDiv: string;
  firstDay?: string;
  lastDay?: string;
  pageContent?: string;
  [key: string]: any;
}

interface ApiResponse {
  data: ProductData;
  success?: boolean;
  message?: string;
}

const ProductViewer: React.FC<ProductViewerProps> = ({ productId, flightState }) => {
  const [loading, setLoading] = useState(false);
  const [productData, setProductData] = useState<ProductData | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [originalData, setOriginalData] = useState<string>("");
  const [isFlightModalVisible, setIsFlightModalVisible] = useState(false);
  const [isProcessingTime, setIsProcessingTime] = useState(false);
  const editorRef = useRef<any>(null);
  const MessageApi = useContext(MessageContext);
  const { t } = useTranslation();

  const { flightInfo, flightList } = flightState || {};

  useEffect(() => {
    const fetchProductData = async () => {
      if (!productId) return;

      setLoading(true);
      setError(null);

      try {
        const response = await fetch(
          `${CONTENT_API_BASE_URL}/apis/ctrip/products/${productId}?lang=${i18n.language}`,
        );

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const result: ApiResponse = await response.json();
        if (result.data && result.data.pageDiv) {
          setProductData(result.data);
          setOriginalData(result.data.pageDiv);
        } else {
          throw new Error(t('productViewer.missingDataOrPageDiv'));
        }
      } catch (err) {
        console.error("获取产品数据失败:", err);
        setError(err instanceof Error ? err.message : t('productViewer.fetchProductDataFailed'));
      } finally {
        setLoading(false);
      }
      const link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = "/public/product_viewer.css"; // 确保路径正确
      document.head.appendChild(link);
      // 清理样式链接
      return () => {
        document.head.removeChild(link);
      };
    };

    fetchProductData();

  }, [productId]);

  useEffect(() => {
    if (flightInfo) {
      handleFlightSelection(flightInfo)
    }
  }, [flightInfo, loading]);

  if (loading) {
    return (
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          height: "200px",
          flexDirection: "column",
          gap: 16,
        }}
      >
        <Spin
          indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
          size="large"
        />
        <Typography.Text type="secondary">
          {t('productViewer.loadingProduct')} (ID: {productId})
        </Typography.Text>
      </div>
    );
  }

  if (error) {
    return (
      <Alert
        message={t('productViewer.loadFailed')}
        description={t('productViewer.loadFailedDesc', { productId, error })}
        type="error"
        showIcon
        style={{ margin: 16 }}
      />
    );
  }

  if (!productData) {
    return (
      <Alert
        message={t('productViewer.noData')}
        description={t('productViewer.noDataDesc', { productId })}
        type="info"
        showIcon
        style={{ margin: 16 }}
      />
    );
  }
  // 提交内容到后端
  const submitContent = async (id: string, pageDiv: string) => {
    try {
      const response = await fetch(
        `${CONTENT_API_BASE_URL}/apis/ctrip/products/updateContent`,
        {
          method: "POST",
          headers: {
            Accept: "*/*",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ id, pageDiv }),
        },
      );
      if (!response.ok) {
        throw new Error(t('productViewer.submitFailed'));
      }
      return await response.json();
    } catch (error) {
      console.error("提交内容出错:", error);
      return null;
    }
  };

  // 保存功能
  const handleSave = async () => {
    if (!productData || !editorRef.current) return;

    // 从编辑器获取当前内容
    const currentContent = editorRef.current.getCurrentData();

    const result = await submitContent(productId, currentContent);
    if (result && result.success) {
      // 保存成功后更新productData和originalData
      setProductData((prev) => ({ ...prev!, pageDiv: currentContent }));
      setOriginalData(currentContent);
      MessageApi.success(t('productViewer.saveSuccess'));
    } else {
      MessageApi.error(`${t('productViewer.saveFailed')}: ${result ? result.message : t('productViewer.unknownError')}`);
    }
  };

  // 重置功能
  const handleReset = () => {
    MessageApi.success(t('productViewer.resetSuccess'));
  };

  // 从 pageContent 中提取第一天和最后一天的标题
  const extractDayTitles = (pageContent: string) => {
    if (!pageContent) {
      return { firstTitle: "", lastDayTitle: "" };
    }

    // 使用分号分割天数
    const days = pageContent
      .split("；")
      .map((day) => day.trim())
      .filter((day) => day.length > 0);
    if (days.length === 0) {
      return { firstTitle: "", lastDayTitle: "" };
    }

    const firstTitle = days[0] || "";
    const lastDayTitle = days[days.length - 1] || "";

    return { firstTitle, lastDayTitle };
  };

  // 处理航班选择
  async function handleFlightSelection(flightInfo: FlightOption) {
    if (!productData) return;
    if (flightInfo.itineraryId === "0") return;
    setIsProcessingTime(true);
    try {
      // 每次选择航班之后，先恢复到原始的pageDiv
      setProductData((prev) => ({ ...prev!, pageDiv: originalData }));

      // 如果在编辑模式，也更新编辑器内容
      if (isEditing && editorRef.current) {
        editorRef.current.setData(originalData);
      }

      // 不要重新保存航班数据到缓存，保持原有的航班列表数据不变
      // 只使用选中的航班进行时间处理
      // 检查是否有 firstDay 和 lastDay 数据
      if (!productData.firstDay || !productData.lastDay) {
        MessageApi.error(t('productViewer.missingDayInfo'));
        return;
      }

      // 检查是否有 pageContent 数据
      if (!productData.pageContent) {
        MessageApi.error(t('productViewer.missingPageContent'));
        return;
      }

      // 从 pageContent 中提取第一天和最后一天的标题
      const { firstTitle, lastDayTitle } = extractDayTitles(
        productData.pageContent,
      );

      // 简化航班信息，只保留时间相关的数据
      const simplifiedFlightInfo = {
        outboundDepartureTime: flightInfo.outboundFlight?.departureTime,
        outboundArrivalTime: flightInfo.outboundFlight?.arrivalTime,
        returnDepartureTime: flightInfo.returnFlight?.departureTime,
        returnArrivalTime: flightInfo.returnFlight?.arrivalTime,
      };

      // 调用时间处理API，传递简化的航班时间信息、第一天和最后一天的内容，以及标题信息
      const timeDataResult = await processTimeData(
        simplifiedFlightInfo,
        productData.firstDay,
        productData.lastDay,
        firstTitle,
        lastDayTitle,
        `chat_${Date.now()}`, // 生成临时的chatId
      );

      // 从原始的 pageDiv 中移除指定的时间数据，并插入航班到达信息
      const updatedPageDiv = removeTimeDataFromPageDiv(
        originalData,
        timeDataResult,
        flightInfo,
      );

      // 更新产品数据
      setProductData((prev) => ({ ...prev!, pageDiv: updatedPageDiv }));

      // 如果在编辑模式，也更新编辑器内容
      if (isEditing && editorRef.current) {
        editorRef.current.setData(updatedPageDiv);
      }

      MessageApi.success(t('productViewer.flightProcessSuccess'));
    } catch (error) {
      console.error("处理航班信息失败:", error);
      MessageApi.error(t('productViewer.flightProcessError'));
    } finally {
      setIsProcessingTime(false);
      setIsFlightModalVisible(false);
    }
  };

  // 根据 API 返回的时间结构从 pageDiv 中移除指定的时间数据
  const removeTimeDataFromPageDiv = (
    pageDiv: string,
    timeDataStructure: TimeDataResult,
    flightInfo?: FlightOption,
  ): string => {
    let updatedPageDiv = pageDiv;

    if (!timeDataStructure) {
      return updatedPageDiv;
    }

    // 首先移除所有空的时间行
    updatedPageDiv = removeEmptyTimeRows(updatedPageDiv,
      flightInfo?.outboundFlight.arrivalTime,
      flightInfo?.returnFlight.departureTime
    );

    // 插入航班到达信息行（在处理移除之前）
    if (flightInfo && flightInfo.outboundFlight) {
      updatedPageDiv = insertFlightArrivalRow(
        updatedPageDiv,
        flightInfo.outboundFlight,
      );
    }

    // 插入航班返程信息行（在最后一个表格）
    if (flightInfo && flightInfo.returnFlight) {
      updatedPageDiv = insertFlightDepartureRow(
        updatedPageDiv,
        flightInfo.returnFlight,
      );
    }

    // 处理 first 数组中的时间
    if (timeDataStructure.first && Array.isArray(timeDataStructure.first)) {
      timeDataStructure.first.forEach((timeValue: string) => {
        updatedPageDiv = removeTimeFromHTML(updatedPageDiv, timeValue);
      });
    }

    // 处理 lastDay 数组中的时间
    if (timeDataStructure.lastDay && Array.isArray(timeDataStructure.lastDay)) {
      timeDataStructure.lastDay.forEach((timeValue: string) => {
        updatedPageDiv = removeTimeFromHTML(updatedPageDiv, timeValue);
      });
    }

    // 更新标题内容
    if (
      timeDataStructure.firstTitle !== undefined ||
      timeDataStructure.lastDayTitle !== undefined
    ) {
      updatedPageDiv = updateDayTitles(
        updatedPageDiv,
        timeDataStructure.firstTitle,
        timeDataStructure.lastDayTitle,
      );
    }

    return updatedPageDiv;
  };

  // 插入航班到达信息行
  const insertFlightArrivalRow = (
    html: string,
    flightInfo?: FlightOption["outboundFlight"],
  ): string => {
    const tempDiv = document.createElement("div");
    const departureTime = flightInfo?.departureTime;
    tempDiv.innerHTML = html;

    // 获取翻译文本
    const flightArrivalTitle = t('productViewer.flightArrival');
    const flightArrivalDesc = t('productViewer.flightArrivalDesc');
    const flightNumberLabel = t('productViewer.flightNumber');
    const departureAirportLabel = t('productViewer.departureAirport');
    const arrivalAirportLabel = t('productViewer.arrivalAirport');
    const departureTimeLabel = t('productViewer.departureTime');
    const arrivalTimeLabel = t('productViewer.arrivalTime');

    // 找到第一个包含 th.print_table_th_right 的表格
    const firstTable = tempDiv.querySelector(
      "table:has(th.print_table_th_right)",
    );
    const titleRow = firstTable?.querySelector(
      "tr:has(th.print_table_th_right)",
    );

    // 创建航班到达信息行
    const arrivalRow = document.createElement("tr");
    const timeOnly = departureTime
      ? departureTime.match(/\d{2}:\d{2}/)?.[0] || ""
      : "";
    arrivalRow.innerHTML = `
      <td>
      <p class="print_table_time">${timeOnly}</p>
      <p class="print_table_time_text"></p>
      </td>
      <td class="print_table_td_right">
      <p class="print_table_title">${flightArrivalTitle}</p>
      <div class="print_table_td_text">
      <div class="rich_content_view_20191129 desc break-words">
      ${flightArrivalDesc}
      </div>
      <div class="rich_content_view_20191129 desc break-words" style="margin-top: 8px; color: #888; font-size: 13px; white-space: pre-line;">
        ${flightInfo
        ?
        `${flightNumberLabel}${flightInfo.flightNumber || ""}
          ${departureAirportLabel}${flightInfo.departureAirport || ""}
          ${arrivalAirportLabel}${flightInfo.arrivalAirport || ""}
          ${departureTimeLabel}${flightInfo.departureTime || ""}
          ${arrivalTimeLabel}${flightInfo.arrivalTime || ""}`
        : ""
      }
      </div>
      </div>
      </td>
    `;

    // 在标题行后插入航班到达行
    titleRow?.insertAdjacentElement("afterend", arrivalRow);

    return tempDiv.innerHTML;
  };

  // 插入航班返程信息行
  const insertFlightDepartureRow = (
    html: string,
    flightInfo: FlightOption["returnFlight"],
  ): string => {
    const tempDiv = document.createElement("div");
    tempDiv.innerHTML = html;
    const departureTime = flightInfo?.departureTime;

    // 获取翻译文本
    const flightDepartureTitle = t('productViewer.flightDeparture');
    const flightDepartureDesc = t('productViewer.flightDepartureDesc');
    const flightNumberLabel = t('productViewer.flightNumber');
    const departureAirportLabel = t('productViewer.departureAirport');
    const arrivalAirportLabel = t('productViewer.arrivalAirport');
    const departureTimeLabel = t('productViewer.departureTime');
    const arrivalTimeLabel = t('productViewer.arrivalTime');

    // 找到所有包含 th.print_table_th_right 的表格
    const tables = tempDiv.querySelectorAll(
      "table:has(th.print_table_th_right)",
    );
    const lastTable = tables[tables.length - 1]; // 最后一个表格

    // 创建航班返程信息行
    const departureRow = document.createElement("tr");
    const timeOnly = departureTime
      ? departureTime.match(/\d{2}:\d{2}/)?.[0] || ""
      : "";
    departureRow.innerHTML = `
      <td>
      <p class="print_table_time">${timeOnly}</p>
      <p class="print_table_time_text"></p>
      </td>
      <td class="print_table_td_right">
      <p class="print_table_title">${flightDepartureTitle}</p>
      <div class="print_table_td_text">
        <div class="rich_content_view_20191129 desc break-words">
        ${flightDepartureDesc}
        </div>
        <div class="rich_content_view_20191129 desc break-words" style="margin-top: 8px; color: #888; font-size: 13px; white-space: pre-line;">
          ${flightInfo
        ?
        `${flightNumberLabel}${flightInfo.flightNumber || ""}
              ${departureAirportLabel}${flightInfo.departureAirport || ""}
              ${arrivalAirportLabel}${flightInfo.arrivalAirport || ""}
              ${departureTimeLabel}${flightInfo.departureTime || ""}
              ${arrivalTimeLabel}${flightInfo.arrivalTime || ""}`
        : ""
      }
        </div>
      </div>
      </td>
    `;

    // 在最后一个表格的最后面插入航班返程行
    lastTable?.appendChild(departureRow);

    return tempDiv.innerHTML;
  };


  // 移除所有空的时间行
  const removeEmptyTimeRows = (html: string, startTime?: string, endTime?: string): string => {
    try {
      // 创建一个临时的DOM容器来解析HTML
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = html;
      // 选出第一个和最后一个 print_table 表格
      const printTables = tempDiv.querySelectorAll("table.print_table");
      const firstTable = printTables[0];
      const lastTable = printTables[printTables.length - 1];
      // 查找所有 class="print_table_time" 的 p 元素
      const firstTimeElements = firstTable.querySelectorAll("p.print_table_time") || [];
      const lastTimeElements = lastTable.querySelectorAll("p.print_table_time") || [];
      const toMinutes = (t: string) => {
        const [h, m] = t.split(":").map(Number);
        return h * 60 + m;
      };

      let removedCount = 0;
      const handleElement = (elements: NodeListOf<Element>, type: "start" | "end") => {

        elements.forEach((timeElement) => {
          const elementText = timeElement.textContent?.trim() || "";

          // 如果时间内容为空，移除整行
          // 如果时间内容为空，或者在航班起止时间区间之外，移除整行
          // 仅当 startTime 和 endTime 都存在且格式为 "HH:mm" 时才进行区间判断
          let shouldRemove = false;

          if (elementText === "") {
            shouldRemove = true;
          } else if (!/^\d{2}:\d{2}$/.test(elementText)) {
            shouldRemove = false;
          } else {
            if (startTime && type === "start") {
              const timeVal = toMinutes(elementText);
              const startVal = toMinutes(startTime.match(/\d{2}:\d{2}/)?.[0] || "");
              if (timeVal <= startVal) {
                shouldRemove = true;
              }
            }
            if (endTime && type === "end") {
              const timeVal = toMinutes(elementText);
              const endVal = toMinutes(endTime.match(/\d{2}:\d{2}/)?.[0] || "");
              if (timeVal >= endVal) {
                shouldRemove = true;
              }
            }
          }

          if (shouldRemove) {
            // 找到父级 td 元素
            const tdElement = timeElement.closest("td");
            if (tdElement) {
              // 找到父级 tr 元素
              const trElement = tdElement.closest("tr");
              if (trElement) {
                trElement.remove();
                removedCount++;
              }
            }
          }
        });
      }

      handleElement(firstTimeElements, "start");
      handleElement(lastTimeElements, "end");

      // 返回修改后的HTML
      return tempDiv.innerHTML;
    } catch (error) {
      console.error("移除空时间行失败:", error);
      return html; // 返回原始HTML
    }
  };

  // 更新页面中的标题内容
  const updateDayTitles = (
    html: string,
    firstTitle?: string,
    lastDayTitle?: string,
  ): string => {
    try {
      // 创建一个临时的DOM容器来解析HTML
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = html;

      // 查找所有 class="print_table_th_right" 的 th 元素
      const titleElements = tempDiv.querySelectorAll("th.print_table_th_right");
      if (titleElements.length > 0) {
        // 更新第一天的标题
        if (firstTitle !== undefined && titleElements[0]) {
          // 如果 firstTitle 为空字符串，设置为 "接机"
          const finalFirstTitle =
            firstTitle.trim() === "" ? t('productViewer.airportPickup') : firstTitle;
          titleElements[0].textContent = finalFirstTitle;
        }

        // 更新最后一天的标题（如果有多天行程）
        if (lastDayTitle !== undefined && titleElements.length > 1) {
          const lastIndex = titleElements.length - 1;
          // 如果 lastDayTitle 为空字符串，设置为 "返程"
          const finalLastDayTitle =
            lastDayTitle.trim() === "" ? t('productViewer.returnTrip') : lastDayTitle;
          titleElements[lastIndex].textContent = finalLastDayTitle;
        }
      } else {
      }

      // 返回修改后的HTML
      return tempDiv.innerHTML;
    } catch (error) {
      console.error("更新标题失败:", error);
      return html; // 返回原始HTML
    }
  };

  // 从HTML中移除特定时间值的辅助函数 - 使用DOM操作
  const removeTimeFromHTML = (html: string, timeValue: string): string => {
    const cleanTimeValue = timeValue.trim();
    try {
      // 创建一个临时的DOM容器来解析HTML
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = html;

      // 查找所有 class="print_table_time" 的 p 元素
      const timeElements = tempDiv.querySelectorAll("p.print_table_time");

      let removed = false;
      timeElements.forEach((timeElement) => {
        const elementText = timeElement.textContent?.trim() || "";

        // 检查时间元素的文本内容是否匹配，或者内容为空
        if (elementText === cleanTimeValue || elementText === "") {
          if (elementText === "") {
          } else {
          }

          // 找到父级 td 元素
          const tdElement = timeElement.closest("td");
          if (tdElement) {
            // 找到父级 tr 元素
            const trElement = tdElement.closest("tr");
            if (trElement) {
              // 移除整个 tr 行
              trElement.remove();
              removed = true;
              if (elementText === "") {
              } else {
              }
            } else {
              timeElement.textContent = "";
            }
          } else {
            timeElement.textContent = "";
          }
        }
      });

      if (!removed && cleanTimeValue !== "") {
        // 如果是时间段描述（如"下午"），查找 print_table_time_text 元素
        if (
          cleanTimeValue === t('productViewer.afternoon') ||
          cleanTimeValue === t('productViewer.morning') ||
          cleanTimeValue === t('productViewer.evening') ||
          cleanTimeValue === t('productViewer.noon')
        ) {
          const timeTextElements = tempDiv.querySelectorAll(
            "p.print_table_time_text",
          );
          timeTextElements.forEach((element) => {
            if (element.textContent?.includes(cleanTimeValue)) {
              element.textContent = "";
            }
          });
        }
      }

      // 返回修改后的HTML
      return tempDiv.innerHTML;
    } catch (error) {
      console.error("DOM操作失败，回退到原始方法:", error);

      // 如果DOM操作失败，回退到简单的字符串替换
      const exactTimePattern = new RegExp(
        `<p[^>]*class="print_table_time"[^>]*>\\s*${cleanTimeValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*</p>`,
        "gi",
      );
      return html.replace(exactTimePattern, '<p class="print_table_time"></p>');
    }
  };

  // 切换编辑模式
  const toggleEditMode = () => {
    setIsEditing(!isEditing);
  };

  return (
    <div
      style={{
        width: "100%",
        height: "100%",
        overflow: "auto",
        backgroundColor: "#fff",
      }}
    >
      <link rel="stylesheet" href="/product_viewer.css" />

      {/* 顶部标题栏 */}
      <div
        style={{
          position: "sticky",
          top: 0,
          zIndex: 1000,
          backgroundColor: "#fff",
          borderBottom: "1px solid #d9d9d9",
          padding: "12px 16px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <Typography.Title level={4} style={{ margin: 0 }}>
          {productData.title || `${t('productViewer.product')} ${productId}`}
        </Typography.Title>

        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <Button
            icon={<SendOutlined />}
            onClick={() => setIsFlightModalVisible(true)}
            loading={isProcessingTime}
            disabled={isEditing}
            type={"default"}
          >
            {t('productViewer.selectFlight')}
          </Button>

          {isEditing && (
            <>
              <Button onClick={handleSave} type="primary">
                {t('productViewer.save')}
              </Button>
              <Button
                onClick={() => {
                  if (editorRef.current) {
                    editorRef.current.reset();
                  }
                }}
              >
                {t('productViewer.reset')}
              </Button>
            </>
          )}

          <Button
            type={isEditing ? "link" : "default"}
            onClick={toggleEditMode}
          >
            {isEditing ? t('productViewer.exitEdit') : t('productViewer.edit')}
          </Button>
        </div>
      </div>

      {/* 内容区域 */}
      <Card
        size="small"
        style={{ margin: 16, marginBottom: 0 }}
        bodyStyle={{ padding: 0 }}
      >
        {isEditing ? (
          <AIEditor
            initialData={productData.pageDiv}
            getData={(data: string) => {
              // 只在这里临时存储编辑的内容，不立即更新productData
              // 实际更新会在保存时进行
            }}
            onSave={handleSave}
            onReset={handleReset}
            ref={editorRef}
          />
        ) : (
          <div
            style={{
              padding: 16,
              minHeight: 400,
            }}
            dangerouslySetInnerHTML={{ __html: productData.pageDiv }}
          />
        )}
      </Card>

      {/* 航班选择模态框 */}
      <CachedFlightSelectionModal
        flights={flightList || []}
        visible={isFlightModalVisible}
        onCancel={() => setIsFlightModalVisible(false)}
        onSelect={handleFlightSelection}
      />
    </div>
  );
};

export default ProductViewer;
